package com.bee.app.util;

import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.util.Date;

import javax.crypto.Cipher;

/**
 * RSA非对称加密
 *
 * @author liuzy
 * @version 2015年5月22日
 */
public class RSA {
	private static PublicKey publicKey;
	private static PrivateKey privateKey;
	private static String publicKeyHexStr;

	private static final String RSA = "RSA";
	private static KeyPairGenerator keyPairGenerator = null;
	private static Cipher cipher = null;

	static {
		try {
			keyPairGenerator = KeyPairGenerator.getInstance(RSA);
			cipher = Cipher.getInstance(RSA);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static String getPublicKey() {
		if (publicKey == null) {
			createKey();
		}
		return publicKeyHexStr;
	}

	/**
	 * 生成服务器公钥和私钥
	 *
	 * @throws Exception
	 */
	public static void createKey() {
		SecureRandom secureRandom = new SecureRandom(new Date().toString().getBytes());
		keyPairGenerator.initialize(1024, secureRandom);
		KeyPair keyPair = keyPairGenerator.generateKeyPair();
		publicKey = keyPair.getPublic();
		privateKey = keyPair.getPrivate();
		publicKeyHexStr = StringKit.bytesToHexStr(publicKey.getEncoded());
		/*
		 * 输出到文件 FileUtil.outKeyFile(publicKey.getEncoded(),
		 * "d:/key/publicKey"); FileUtil.outKeyFile(privateKey.getEncoded(),
		 * "d:/key/privateKey");
		 */
	}

	/**
	 * 公钥加密
	 *
	 * @param msg
	 * @return
	 */
	public static String encode(String msg) {
		try {
			cipher.init(Cipher.ENCRYPT_MODE, publicKey);
			byte[] bytes = cipher.doFinal(msg.getBytes());
			return StringKit.bytesToHexStr(bytes);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * 私钥解密
	 *
	 * @param hexMsg
	 * @return
	 */
	public static String decode(String hexMsg) {
		try {
			cipher.init(Cipher.DECRYPT_MODE, privateKey);
			byte[] bytes = cipher.doFinal(StringKit.hexStrToBytes(hexMsg));
			return new String(bytes);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

}
